import React from "react";
import {inject, observer} from "mobx-react";
import {withRouter} from "react-router-dom";
import {Form, TabPage, ListViewPage, Browser} from "weaver-mobile-page";
import {
    Icon,
    Tools,
    ActionSheet,
    SearchBar,
    List,
    DatePicker,
    ActivityIndicator,
    Bubble,
    Progress
} from "weaver-mobile";
import {forwardViewForm} from "../../../workflowForm/util/forwardPage";
import {getRouteParams, getUrlParams, openLink} from "../../util";

import ReplyEditor from "../reply/replyEditor";
import FloatingBtn from "../../public/FloatingBtn";
import * as Tm from "../template";

const getLabel = Tools.getLabel;

const isIPhone = new RegExp("\\biPhone\\b|\\biPod\\b", "i").test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject("taskDetailsStore")
@observer
export default class TaskDetails extends React.Component {
    componentWillMount() {
        this.Init(this.props);
    }

    componentWillReceiveProps(nextProps, nextContext) {
        if (nextProps.match.params.taskid !== this.props.match.params.taskid ||
            nextProps.match.params.index !== this.props.match.params.index ||
            nextProps.match.params.viewtype !== this.props.match.params.viewtype) {
            this.Init(nextProps);
        }
    }

    Init = (props) => {
        if (!props) {
            props = this.props;
        }
        const {taskDetailsStore, history} = props;
        const {index, taskid} = getRouteParams(props);
        const {parentid} = getUrlParams(props.location.search)
        taskDetailsStore.init(index, taskid, history, parentid)

    };
    showActionSheet = () => {
        const {taskDetailsStore: {taskid, prjid, tabIndex, rightMenus, changeStateTo, deleteCard}, history} = this.props;
        const {btn_edit, btn_add, btn_delete, btn_onSubmit, btn_onApprove} = rightMenus;
        const BUTTONS = [{
            content: getLabel("31129", "取消")
        }];

        if (btn_onSubmit) {
            BUTTONS.unshift({
                content: getLabel("15143", "提交审批"), onClick: () => {
                    changeStateTo("submitplan")
                }
            });
        }
        if (btn_onApprove) {
            BUTTONS.unshift({
                content: getLabel("83909", "提交执行"), onClick: () => {
                    changeStateTo("approveplan")
                }
            });
        }
        if (btn_delete) {
            BUTTONS.unshift({content: getLabel("91", "删除"), onClick: () => deleteCard()});
        }

        if (btn_edit) {
            BUTTONS.unshift({
                content: getLabel("26473", "编辑"), onClick: () => {
                    history.push(`/FormOperations?taskid=${taskid}&viewtype=edit`);
                }
            });
        }
        if (btn_add) {
            BUTTONS.unshift({
                content: getLabel("1421", "新增"), onClick: () => {
                    if (tabIndex === 1) {
                        history.push(`/FormOperations?parentid=${taskid}&prjid=${prjid}&viewtype=add`);
                    }
                    //else if (tabIndex === 0) {
                    //     history.push(`/FormOperations?taskid=${taskid}&viewtype=add`);
                    // }
                }
            });
        }
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            maskClosable: true,
            "data-seed": "logId",
            wrapProps,
        });
    };

    renderForm = () => {
        const {form, formChange, linkToAccessory} = this.props.taskDetailsStore;
        const {conditioninfo, isInit} = form;
        const fields = [];
        if (isInit) {
            let accessoryContents = [];
            conditioninfo.forEach((group) => {
                group.items.forEach((field) => {
                    if (field.conditionType === "PRJDATETIME") {
                            fields.push(<DatePicker
                                style={{textAlign: "center"}}
                                key={field.domkey.join("__")}
                                value={field.value[0] === "" ? "" : (field.value[1] === "" ? [field.value[0], field.value[1]].join(" ") + "00:00" : [field.value[0], field.value[1]].join(" "))}
                                extra={<span/>}
                                disabled
                            >
                                <List.Item arrow="horizontal">{field.label}</List.Item>
                            </DatePicker>)
                    } else if (field.domkey[0] === "finish") {
                        fields.push(
                            <List className="my-list" key={field.domkey.join("__")}>
                                <List.Item extra={
                                    <div className="proj-show-info">
                                        <div className="progress"><Progress percent={field.value} position="normal"/>
                                        </div>
                                        <div aria-hidden="true"><span className="progress-text">{field.value}%</span>
                                        </div>
                                    </div>
                                }>{field.label}</List.Item>
                            </List>)
                    } else {
                        fields.push(<Form.Item
                            key={field.domkey.join("__")}
                            form={form}
                            fieldConfig={field}
                            onChange={() => [formChange(field)]}
                        />);
                    }

                });
            });
        }
        return fields;
    }


    render() {
        const {
            history,
            taskDetailsStore: {
                isLoading, tabIndex, onTabChange, ChildTaskList, comment, TaskRelativeReqList, taskid,
                TaskRelativeDocList, searchValue, searchValue1, changeSearchValue, rightMenus, hasRight,
                browser, browserValue, browser2, browserValue2, addRelativeFile, deleteRelativeFile, setPage,
            }
        } = this.props;

        const tabPageConf = {
            tabs: [
                {title: getLabel("81711", "基本信息"), index: 0},
                {title: getLabel("2098", "子任务"), index: 1},
                {title: getLabel("15153", "相关交流"), index: 2},
                {title: getLabel("22105", "相关流程"), index: 3},
                {title: getLabel("857", "相关文档"), index: 4}],
            btns: [
                <Icon type="ellipsis" onClick={this.showActionSheet.bind(this)}/>
            ],
            props: {
                onChange: (tab) => onTabChange(tab.index, history),
                initialPage: 0,     //初始化tab
                page: tabIndex//当前tab
            }
        };

        return (
            <div className='tab-page-wrapper'>
                {!hasRight ?
                    <div className="no-right-page">
                        <Bubble.Bubble
                            type={12}
                            propmt={getLabel("2012", "对不起，您暂时没有权限！")}/>
                    </div>
                    :
                    <div style={{height: "100%"}}>
                        <TabPage
                            className='proj-tab-page'
                            tabs={tabPageConf.tabs}
                            btns={JSON.stringify(rightMenus) !== "{}" && tabIndex !== 3 && tabIndex !== 4 ?
                                tabPageConf.btns : false}
                            tabProps={tabPageConf.props}
                        />
                        <div className="proj-details-info-wrapper">
                            {tabIndex === 0 ?
                                <div>
                                    {isLoading ?
                                        (<div className='loading'><ActivityIndicator animating size='large'/></div>) :
                                        <Form style={{height: "100%"}}>
                                            <List className="prj-self-form prj-data-picker-css-style">
                                                {this.renderForm()}
                                            </List>
                                        </Form>
                                    }
                                </div> : null}
                            {tabIndex === 1 ? <div>
                                <ListViewPage.Normal
                                    rowKey="id"
                                    store={ChildTaskList}
                                    heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                    getTemplate={Tm.getTaskListTemplate}
                                    onRowClick={(item) => {
                                        history.push(`/TaskDetails/0/${item.id}?parentid=${taskid}`)
                                    }}
                                />
                            </div> : null}
                            {tabIndex === 2 ? <div style={{height: "100%"}}>
                                <ReplyEditor
                                    replyStore={comment}
                                    sortid={taskid}
                                    discusstype="PT"
                                    onReload={(page = 1) => {
                                        setPage(page)
                                    }}/>
                            </div> : null}
                            {tabIndex === 3 ? <div>
                                {rightMenus["btn_add"] ? <FloatingBtn
                                    onClick={() => {
                                        history.push(`/TaskDetails/3/${taskid}/search-history`)
                                    }}
                                    icon={<i className={"floating-icon-self icon-proj icon-jiahao"}/>}
                                /> : null}
                                <div style={{display: "none"}}>
                                    <Browser
                                        label={getLabel("30045", "流程")} store={browser}
                                        hasAdvanceSerach
                                        type={16}
                                        onChange={(id) => {
                                            if (id) {
                                                addRelativeFile(id, "workflow", history)
                                            }
                                        }}
                                        valueArray={browserValue}
                                    />
                                </div>
                                <SearchBar
                                    className="search-select"
                                    placeholder="Search"
                                    value={searchValue}
                                    onChange={(val) => changeSearchValue(val)}
                                    onSubmit={() => this.Init()}
                                    onClear={() => {
                                        changeSearchValue();
                                        this.Init();
                                    }}
                                />
                                <div>
                                    <ListViewPage.Normal
                                        rowKey="id"
                                        store={TaskRelativeReqList}
                                        getTemplate={Tm.getWorkflowTemplate}
                                        heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                        onRowClick={(item) => {
                                            forwardViewForm({
                                                requestid: item.requestid,
                                                f_weaver_belongto_userid: ""
                                            }, (arg) => {
                                                //刷新流程中心
                                            }, "portal")
                                        }}
                                        withSwipeAction={rightMenus["btn_delete"] === true}
                                        swipeActionProps={{
                                            autoClose: true,
                                            right: [
                                                {
                                                    text: getLabel("91", "删除"), style: {
                                                        backgroundColor: "#f4333c",
                                                        color: "#fff",
                                                        padding: "0 8px"
                                                    },
                                                    onPress: (data) => {
                                                        deleteRelativeFile(data.id, "workflow", history)
                                                    },
                                                }]
                                        }}
                                    />
                                </div>
                            </div> : null}
                            {tabIndex === 4 ? <div>
                                {rightMenus["btn_add"] ? <FloatingBtn
                                    onClick={() => {
                                        history.push(`/TaskDetails/4/${taskid}/search-history`)
                                    }}
                                    icon={<i className={"floating-icon-self icon-proj icon-jiahao"}/>}
                                /> : null}
                                <div style={{display: "none"}}>
                                    <Browser
                                        label={getLabel("22243", "文档")} store={browser2}
                                        hasAdvanceSerach
                                        type={9}
                                        onChange={(id) => {
                                            if (id) {
                                                addRelativeFile(id, "doc", history)
                                            }
                                        }}
                                        valueArray={browserValue2}
                                    />
                                </div>
                                <SearchBar
                                    className="search-select"
                                    placeholder="Search"
                                    value={searchValue1}
                                    onChange={(val) => changeSearchValue(val)}
                                    onSubmit={() => this.Init()}
                                    onClear={() => {
                                        changeSearchValue();
                                        this.Init();
                                    }}
                                />
                                <div>
                                    <ListViewPage.Normal
                                        rowKey="id"
                                        store={TaskRelativeDocList}
                                        heightSpace={window.getThemeVars ? window.getThemeVars()["tab-bar-height"] : 50}
                                        getTemplate={Tm.getDocumentTemplate}
                                        onRowClick={(item) => {
                                            openLink("doc", item.docid)
                                        }}
                                        withSwipeAction={rightMenus["btn_delete"] === true}
                                        swipeActionProps={{
                                            autoClose: true,
                                            right: [{
                                                text: getLabel("91", "删除"), style: {
                                                    backgroundColor: "#f4333c",
                                                    color: "#fff",
                                                    padding: "0 8px"
                                                },
                                                onPress: (data) => {
                                                    deleteRelativeFile(data.realid, "doc", history)
                                                },
                                            }]
                                        }}
                                    />
                                </div>
                            </div> : null}
                        </div>
                    </div>}
            </div>
        )
    }
}
